package io.wdb.wxapp.controller;

import java.util.Date;
import java.util.Map;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wdb.exchange.model.RespModel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.wdb.common.exception.RRException;
import io.wdb.common.exception.RspCodeEnum;
import io.wdb.common.utils.CommonUtil;
import io.wdb.common.utils.ConstantConfig;
import io.wdb.common.utils.HttpRequestUtil;
import io.wdb.common.utils.R;
import io.wdb.modules.activity.wxapp.entity.HdScanActivityEntity;
import io.wdb.modules.activity.wxapp.entity.HdScanConfigEntity;
import io.wdb.modules.activity.wxapp.service.HdScanActivityService;
import io.wdb.modules.activity.wxapp.service.HdScanConfigService;
import net.sf.json.JSONObject;

//给小程序扫码加钱用的
@Controller
@RequestMapping("scan")
@Api(tags="C.scanActivity api" )
public class ScanQrcodeAddMoneyController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(ScanQrcodeAddMoneyController.class);
	// 根据二维码信息，添加赠送金额
	@Autowired
	private HdScanActivityService hdScanActivityService;
	@Autowired
	private HdScanConfigService hdScanConfigService;

	@RequestMapping(value="scanActivity",method = RequestMethod.POST)
	@ApiOperation(value="扫描二维码活动加钱", notes="根据用户手机号/hdUserId添加用户money")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "hdUserId",value = "微信活动id", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "mobile",value = "手机号", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "userToken",value = "登录token", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "area",value = "扫码地址(获取书柜定位地址)", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "scanCode",value = "扫码字符串", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "sign",value = "sign", dataType = "String", paramType = "query", required=false)
		
	})
	@ResponseBody
	public synchronized R scanActivity(HttpServletRequest request) {
		String mobile = request.getParameter("mobile");
		String sign = request.getParameter("sign");
		String userToken = request.getParameter("userToken");
		String area = request.getParameter("area");
		String hdUserId = request.getParameter("hdUserId");
		String scanCode = request.getParameter("scanCode");
		
		logger.info("scanActivity mobile:{},userToken:{},hdUserId{}",mobile,userToken,hdUserId);
		
		checkIsNull(userToken, "userToken");
		//如果前端未传mobile，根据userToken
		
		if("null".equals(mobile)) mobile = null;
		
		checkIsNull(mobile, "mobile");
		checkIsNull(scanCode, "scanCode");
		
		//根据scanCode获取详情
		HdScanConfigEntity hdScanConfigEntity =  hdScanConfigService.queryObject(scanCode);
		if(hdScanConfigEntity == null || hdScanConfigEntity.getStatus() == 0) {
			return R.error(RspCodeEnum.CODE_ACT_QR_ERROR.getRspCode(), RspCodeEnum.CODE_ACT_QR_ERROR.getRspMsg());
		}
		
		if(hdScanConfigEntity.getLimitTimes() < 2) {//仅允许扫码获得一次
			Map<String, Object> map = new HashMap<>();
			map.put("mobile", mobile);
			List<HdScanActivityEntity> enList = hdScanActivityService.queryList(map);
			if(enList != null && enList.size() > 0) {
				return R.error(RspCodeEnum.CODE_ACT_QR_REPEAT.getRspCode(), RspCodeEnum.CODE_ACT_QR_REPEAT.getRspMsg());
			}
		}
		//地推扫码 加钱
		int sendMoney = hdScanConfigEntity.getMoney();
		String returnMsg = (sendMoney/100)+"元";
		RespModel respModel = null;
		if (hdScanConfigEntity.getChannel().equals(ConstantConfig.SCAN_ADD_MONEY)) {
			respModel = apiServiceHandler.presentAmount(sendMoney, mobile);
			
		}else if(hdScanConfigEntity.getChannel().equals(ConstantConfig.SCAN_ADD_VIP_MONTH)) {//加月卡
			respModel = apiServiceHandler.presentVIP(mobile, 1, 0);
			returnMsg = "月卡";
		}
		
		//TODO 添加扫码加钱记录
		HdScanActivityEntity hdScanActivity = new HdScanActivityEntity();
		hdScanActivity.setCreateTime(new Date());
		hdScanActivity.setArea(area);
		hdScanActivity.setHdUserId(hdUserId);
		hdScanActivity.setMobile(mobile);
		hdScanActivity.setHdScanConfigId(scanCode);
		hdScanActivity.setMoney(sendMoney);
		if(respModel != null && respModel.getCode() == 0) {
			hdScanActivity.setStatus(1);
		}else {
			logger.info("scan qrcode add vip error mobile[{}],info[{}]",mobile, respModel);
		}
		
		hdScanActivityService.save(hdScanActivity);
		//保存活动场地、活动时间、工作人员、工作人员对应的二维码、单个工作人员二维码对应的扫码次数 及赠送金额次数、赠送金额总计
		Map<String, Object> result = new HashMap<>();
		
		result.put("money", returnMsg);
		result.put("area", hdScanConfigEntity.getArea());
		result.put("createTime", hdScanActivity.getCreateTime());
		
		return R.ok(result);
	}
	
	@RequestMapping(value="scanActivityByPhone",method = RequestMethod.POST)
	@ApiOperation(value="扫描二维码活动加钱", notes="根据用户手机号添加活动奖励，未注册，先注册，注册后直接添加到用户账户")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "mobile",value = "手机号", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "userToken",value = "登录token", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "area",value = "扫码地址(获取书柜定位地址)", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "scanCode",value = "扫码字符串", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "verify_code",value = "verify_code", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "sign",value = "sign", dataType = "String", paramType = "query", required=false)
		
	})
	@ResponseBody
	public synchronized R scanActivityByPhone(HttpServletRequest request) {
		String mobile = request.getParameter("mobile");
		String code = request.getParameter("verify_code");
		String sign = request.getParameter("sign");
		String area = request.getParameter("area");
		String scanCode = request.getParameter("scanCode");
		
		logger.info("h5 page add activity info by phone {} and code {}",mobile,code);
		checkIsNull(code, "verify_code");

		//登录
		RespModel respModel = apiServiceHandler.activityLogin("h5Activity", mobile, code);
		if(isEmpty(respModel)) {
			throw new RRException(RspCodeEnum.CODE_SYS_ERROR);
		}else if(respModel.getCode() != 0) {
			throw new RRException(respModel.getMsg(), respModel.getCode());
		}
		
		if("null".equals(mobile)) mobile = null;
		
		checkIsNull(mobile, "mobile");
		checkIsNull(scanCode, "scanCode");
		
		//根据scanCode获取详情
		HdScanConfigEntity hdScanConfigEntity =  hdScanConfigService.queryObject(scanCode);
		if(hdScanConfigEntity == null || hdScanConfigEntity.getStatus() == 0) {
			return R.error(RspCodeEnum.CODE_ACT_QR_ERROR.getRspCode(), RspCodeEnum.CODE_ACT_QR_ERROR.getRspMsg());
		}
		
		if(hdScanConfigEntity.getLimitTimes() < 2) {//仅允许扫码获得一次
			Map<String, Object> map = new HashMap<>();
			map.put("mobile", mobile);
			List<HdScanActivityEntity> enList = hdScanActivityService.queryList(map);
			if(enList != null && enList.size() > 0) {
				return R.error(RspCodeEnum.CODE_ACT_QR_REPEAT.getRspCode(), RspCodeEnum.CODE_ACT_QR_REPEAT.getRspMsg());
			}
		}
		//地推扫码 加钱
		int sendMoney = hdScanConfigEntity.getMoney();
		String returnMsg = (sendMoney/100)+"元";
		
		RespModel respModelPresent = null;
		if (hdScanConfigEntity.getChannel().equals(ConstantConfig.SCAN_ADD_MONEY)) {
			respModelPresent = apiServiceHandler.presentAmount(sendMoney, mobile);
			
		}else if(hdScanConfigEntity.getChannel().equals(ConstantConfig.SCAN_ADD_VIP_MONTH)) {//加月卡
			respModelPresent = apiServiceHandler.presentVIP(mobile, 1, 0);
			returnMsg = "月卡";
		}
		
		//TODO 添加扫码加钱记录
		HdScanActivityEntity hdScanActivity = new HdScanActivityEntity();
		hdScanActivity.setCreateTime(new Date());
		hdScanActivity.setArea(area);
		hdScanActivity.setMobile(mobile);
		hdScanActivity.setHdScanConfigId(scanCode);
		hdScanActivity.setMoney(sendMoney);
		if(respModelPresent != null && 0 == respModelPresent.getCode()) {
			hdScanActivity.setStatus(1);
		}
		
		hdScanActivityService.save(hdScanActivity);
		//保存活动场地、活动时间、工作人员、工作人员对应的二维码、单个工作人员二维码对应的扫码次数 及赠送金额次数、赠送金额总计
		Map<String, Object> result = new HashMap<>();
		
		result.put("money", returnMsg);
		result.put("area", hdScanConfigEntity.getArea());
		result.put("createTime", hdScanActivity.getCreateTime());
		
		return R.ok(result);
	}
	
	//返回链接
	@RequestMapping(value="scanQrCodeUrl",method = RequestMethod.POST)
	@ApiOperation(value="扫描二维码活动加钱配置", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "area",value = "活动地址", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "channel",value = "渠道，默认为1", dataType = "String", paramType = "query", required=false),
		@ApiImplicitParam(name = "limitTimes",value = "没人允许获得次数，默认1", dataType = "String", paramType = "query", required=false),
		@ApiImplicitParam(name = "money",value = "二维码活动赠钱数量(分)", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "worker",value = "工作人员", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "user",value = "登录密码", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "sign",value = "sign", dataType = "String", paramType = "query", required=false)
		
	})
	@ResponseBody
	public R scanQrCodeUrl(HttpServletRequest request) {
		//用户名和密码
		String qrcode = "";
		if(request.getParameter("user").equals("#wdb007#")) {
			String area = request.getParameter("area");
			String channel = request.getParameter("channel");
			String limitTimes = request.getParameter("limitTimes");
			String money = request.getParameter("money");
			String worker = request.getParameter("worker");
			
			HdScanConfigEntity entity = new HdScanConfigEntity();
			entity.setArea(area);
			if(ObjectUtils.isEmpty(channel)) {
				entity.setChannel(1);
			}else {
				entity.setChannel(Integer.valueOf(channel));
			}
			entity.setCreateTime(new Date());
			if(ObjectUtils.isEmpty("limitTimes")) {
				entity.setLimitTimes(1);
			}else {
				entity.setLimitTimes(Integer.valueOf(limitTimes));
			}
			
			entity.setMoney(Integer.valueOf(money));
			entity.setStatus(1);
			entity.setWorker(worker);
			qrcode = hdScanConfigService.save(entity);
			
		}
		
		
		return R.ok(qrcode);
	}
	
}
